import { createFishingSession } from "../../../api/fishing-session";

Page({
  data: {
    editable: true,
    // 押金
    deposit: "",
    date: "",
    // 基本信息
    baseInfo: {
      timerange: "09:00-18:00",
      fishingway: "正钓",
      promotion: "",
      // "实放2000斤模特鲈，规格0.8-1.5斤，没有大肚子，皮毛相当巴适，活性高。9点统一下竿，6点收竿。美女、儿童七折优惠。",
    },
    // 放鱼信息数据
    fishStockData: [
      // {
      //   datetime: "2025/11/11 12:00:10",
      //   fish: "鲈鱼",
      //   spec: "2-3斤/条",
      //   amount: "1000斤",
      // },
    ],
    // 回鱼信息
    fishReturnData: [
      // {
      //   mode: "渔获自由",
      //   fish: "鲈鱼",
      //   price: "100",
      //   unit: "斤",
      // },
    ],
    // 标鱼信息数据
    tagFishData: [
      // { name: "蓝标", prize: "斯泰拉", count: 1, condition: "满80人" },
      // { name: "红标", prize: "50元", count: 10, condition: "无" },
    ],
    // 费用信息
    feeData: [
      // {
      //   name: "全天票",
      //   price: 120,
      //   price_early: 100,
      //   price_discount: 90,
      //   stock: 100,
      // },
    ],
  },

  async onLoad(options) {
    console.log("=== page editing onLoad===", options);
    this.eventChannel = this.getOpenerEventChannel();
    const date = options.date || "";
    this.setData({
      date,
    });
  },

  // 通用的字段保存事件
  onFieldSave(e) {
    const { field, detail } = e.detail;
    const { index, data, value } = detail;
    const currentData = this.data[field];

    switch (field) {
      case "baseInfo":
        console.log("===onFieldSave===baseInfo====", data);
        this.setData({ [field]: data });
        break;
      case "deposit":
        this.setData({ [field]: value });
        break;
      default: {
        // 数组类型
        if (index === -1) {
          // 新增
          currentData.push(data);
        } else {
          // 编辑
          currentData[index] = data;
        }
        this.setData({ [field]: currentData });
      }
    }
  },

  // 通用的字段删除事件
  onFieldDelete(e) {
    const { field, detail } = e.detail;
    const { index } = detail;
    const currentData = this.data[field];

    currentData.splice(index, 1);
    this.setData({ [field]: currentData });
  },
  validateForm() {
    const {
      deposit,
      baseInfo,
      fishStockData,
      fishReturnData,
      tagFishData,
      feeData,
    } = this.data;
    const formData = {
      deposit,
      ...baseInfo,
      fishingTags: tagFishData,
      fishingReleases: fishStockData,
      fishingReturns: fishReturnData,
      fishingTickets: feeData,
    };

    console.log("===validateForm==formData====", formData);

    const array = [
      { key: "timerange", title: "请选择放钓时间" },
      { key: "fishingway", title: "请选择放钓方式" },
      { key: "fishingReturns", title: "回鱼信息不能为空" },
      { key: "deposit", title: "请输入押金" },
      { key: "fishingTickets", title: "收费信息不能为空" },
    ];
    const data = formData;
    for (let index = 0; index < array.length; index++) {
      const item = array[index];
      const { key, title } = item;
      let value = formData[key];
      if (typeof value === "string") {
        value = value.trim();
      }
      if (!value || value.length === 0) {
        wx.showToast({
          title,
          icon: "none",
        });
        return false;
      }
      data[key] = value;
    }
    return data;
  },
  // 确认保存
  async onConfirm() {
    const data = this.validateForm();
    if (!data) {
      return;
    }
    const spotId = getApp().globalData.spotId;
    // 添加全局数据
    data.spotId = spotId;
    data.date = this.data.date;

    console.log("===onConfirm==data====", data);
    wx.showLoading({
      title: "提交中...",
    });
    try {
      const result = await createFishingSession(data);
      if (result.error) {
        throw result.error;
      }
      console.log("===save==res====", result);
      wx.hideLoading();
      wx.showToast({
        title: "保存成功",
        icon: "success",
      });
      this.eventChannel.emit("addSuccess", { newItem: result.data });
      setTimeout(() => {
        wx.navigateBack();
      }, 1000);
    } catch (error) {
      wx.hideLoading();
      console.error("保存信息失败:", error);
      wx.showToast({
        title: "保存失败: " + (error.message || "网络错误"),
        icon: "none",
        duration: 3000,
      });
    }
  },
});
